import { Component, OnInit } from '@angular/core';

import { ModalController, NavController, ActionSheetController, PickerController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { AuthService } from 'src/app/services/auth.service';
import * as constants from '../../../providers/Constants'
import { ToastService } from './../../../providers/toast/toast.service'
import { ActivatedRoute, Params } from '@angular/router';
import { ApiRead } from 'src/app/services/api.read';
import { AddressStateListComponent } from 'src/app/component/address-state-list/address-state-list.component';
import { Storage } from 'src/app/providers/Storage';
@Component({
  selector: 'app-address-edit',
  templateUrl: './address-edit.page.html',
  styleUrls: ['./address-edit.page.scss'],
})
export class AddressEditPage implements OnInit {
  editType: number = 0; // 0是新增   1修改删除
  name: string = ''; // 姓名
  phone: string = ''; // 电话
  street: string = ''; // 街道
  house: string = ''; // 门牌号
  city: string = ''; // 门牌号
  mailbox: string = ''; //  邮箱号
  province: string = ''; //  洲份/省
  addressDetail: string = null; // 详细地址
  state: string = 'United States'; // 国家
  addressId: string = '';
  isDefault: boolean = false;
  defaultColumnOptions = [
    [
      '男',
      '女',
      '保密',
    ]
  ]
  constructor(private modalController: ModalController, private activeRoute: ActivatedRoute,
    private auth: AuthService,
    private navController: NavController,
    private apiRead: ApiRead,
    private actionSheetController: ActionSheetController,
    private pickerController: PickerController,
    private toast: ToastService, private http: HttpClient) {
    this.activeRoute.queryParams.subscribe((params: Params) => {
      if (params.edit == 1) {
        let addressItem = JSON.parse(params.addressItem);
        // this.editType = addressItem.addressType;
        this.editType = params.edit;
        this.name = addressItem.addressUserName;
        this.addressDetail = addressItem.address;
        this.phone = addressItem.addressPhone;
        this.addressId = addressItem.addressId;
        this.isDefault = addressItem.addressType==0?true:false;

        this.state = addressItem.country;
        this.street = addressItem.way;
        this.province = addressItem.province;
        this.city = addressItem.city;
        this.house = addressItem.address;
        this.mailbox = addressItem.mailbox;
      }
    });

  }

  ngOnInit() {



  }
  onAddress() {
    this.presentModal();
  }
  updataState() {
    this.presentModal();
    // this.openPicker(1,480,this.defaultColumnOptions,res=>{
    //   this.state=JSON.parse(res).text;
    // });
  }
  async openPicker(numColumns = 1, numOptions = 5, multiColumnOptions, callback) {
    const picker = await this.pickerController.create({
      columns: this.getColumns(numColumns, numOptions, multiColumnOptions),
      cssClass: 'picker-controller',
      buttons: [
        {
          // cssClass:'white',
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'OK',
          handler: value => {
            // console.log(`Got Value ${value}`);

            callback(JSON.stringify(value.data))
          }
        }
      ]
    });
    await picker.present();
  }
  getColumns(numColumns, numOptions, columnOptions) {
    let columns = [];
    for (let i = 0; i < numColumns; i++) {
      columns.push({
        // name: `col-${i}`,
        name: `data`,
        options: this.getColumnOptions(i, numOptions, columnOptions)
      });
    }
    return columns;
  }
  getColumnOptions(columnIndex, numOptions, columnOptions) {
    let options = [];
    for (let i = 0; i < numOptions; i++) {
      options.push({
        text: columnOptions[columnIndex][i % numOptions],
        value: i
      });
    }
    return options;
  }
  submit() {
    console.log(this.state)
    if (!this.name) {
      this.toast.show('Please input your name');
    }else  if (!this.state) {
      this.toast.show('United States');
    }else  if (!this.street) {
      this.toast.show('Please input your street');
    } else if (!this.phone) {
      this.toast.show('Please input your Phone');
    } else {
      this.addAddress();
    }
  }
  // 保存地址信息
  addAddress() {
    let data = {
      addressUserName: this.name,
      // addressTel:this.anntherPhoneNumber,//备选电话
      addressPhone: this.phone,
      country: this.state,  //国家
      province: this.province,  //省
      city: this.city,  //市
      // arear: this.street,  //区
      way: this.street,  //街道
      address: this.house,  //门牌号
      mailbox: this.mailbox,  //门牌号
      // address: this.addressDetail,//地址
      addressType: this.isDefault == true ? '0' : '1',  // 0是默认
      addressId: ''
    }


  
    if (this.editType != 1) {
      this.auth.addAddress(data).subscribe(res => {
        // 保存成功返沪上一页，否则弹出提示框
        if (res.retCode == '000000') {
          // this.toast.show("保存成功");
          this.navController.pop();
        } else if (constants.errCode[res.retCode]) {
          if (constants.errCode[res.retCode] != '0') {
            this.toast.show(constants.errCode[res.retCode]);
          }
        } else if (res.retMsg) {
          this.toast.show(res.retMsg);
        } else {
          this.toast.show("exception service routine");
        }
      });
    } else {
      data.addressId = this.addressId;
      this.auth.upAddress(data).subscribe(res => {
        // 保存成功返沪上一页，否则弹出提示框
        if (res.retCode == '000000') {
          // this.toast.show("保存成功");
          this.navController.pop();
        } else if (constants.errCode[res.retCode]) {
          if (constants.errCode[res.retCode] != '0') {
            this.toast.show(constants.errCode[res.retCode]);
          }
        } else if (res.retMsg) {
          this.toast.show(res.retMsg);
        } else {
          this.toast.show("exception service routine");
        }
      });
    }

  }


  async presentModal() {
    const modal = await this.modalController.create({
      component: AddressStateListComponent,
      // cssClass: 'address-component',
      showBackdrop: true,
      mode: 'md',
      componentProps: {
        // shopDetail: JSON.stringify(this.shopDetail),
        // isShow: this.isShow, shopId: this.shopId,
        // merchCode: this.merchCode,
        // type: type,
        // procList: this.procList
      }
    });

    await modal.present();
    //监听销毁的事件
    const { data } = await modal.onDidDismiss();
    this.state = data.str;
    console.log(data);


  }
  btnDel() {
    this.presentActionSheet();
  }
  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: 'Are you sure you want to delete the address? ',
      mode: 'ios',
      cssClass: 'exit-action-sheet',
      buttons: [{
        text: 'YES',
        handler: () => {
          this.delete();
        }
      }, {
        text: 'NO',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }
  delete() {
    this.auth.deleteAddress({ 'addressId': this.addressId }).subscribe(res => {
      // 保存成功返沪上一页，否则弹出提示框
      if (res.retCode == '000000') {
        this.toast.show('Successfully deleted');
        Storage.sessionStorage.remove('addressItem');
        this.navController.pop();
      } else if (constants.errCode[res.retCode]) {
        if (constants.errCode[res.retCode] != '0') { if (constants.errCode[res.retCode] != '0') { if (constants.errCode[res.retCode] != '0') { if (constants.errCode[res.retCode] != '0') { if (constants.errCode[res.retCode] != '0') { this.toast.show(constants.errCode[res.retCode]); } } } } }
      } else if (res.retMsg) {
        this.toast.show(res.retMsg);
      } else {
        this.toast.show("exception service routine");
      }
    }, err => {
      console.log('失败了-------------------' + event);
    });
  }
}
